package com.wangzhixuan.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wangzhixuan.apiController.BaseInfoApiController;
import com.wangzhixuan.commons.constant.ApiCode;
import com.wangzhixuan.commons.constant.Constants;
import com.wangzhixuan.commons.easemob.Entry;
import com.wangzhixuan.commons.easemob.model.TalkNode;
import com.wangzhixuan.commons.easemob.service.TalkDataService;
import com.wangzhixuan.commons.jiguang.PushUtils;
import com.wangzhixuan.commons.scan.MyException;
import com.wangzhixuan.commons.utils.HttpClientUtil;
import com.wangzhixuan.commons.utils.NumberUtils;
import com.wangzhixuan.commons.utils.PageInfo;
import com.wangzhixuan.commons.utils.date.DateStyle;
import com.wangzhixuan.commons.utils.date.DateUtil;
import com.wangzhixuan.commons.utils.excel.ExcelForGdtask;
import com.wangzhixuan.commons.utils.word.CreatDoc;
import com.wangzhixuan.commons.utils.word.CreatWordFtl;
import com.wangzhixuan.mapper.AnalysisMapper;
import com.wangzhixuan.mapper.BaseInfoMapper;
import com.wangzhixuan.mapper.CategoryMapper;
import com.wangzhixuan.mapper.DescribeMapper;
import com.wangzhixuan.mapper.ImageMapper;
import com.wangzhixuan.mapper.MeetingMapper;
import com.wangzhixuan.mapper.PeopleSignMapper;
import com.wangzhixuan.mapper.PeopleWorkMapper;
import com.wangzhixuan.mapper.RankMapper;
import com.wangzhixuan.mapper.UserMapper;
import com.wangzhixuan.model.BaseInfo;
import com.wangzhixuan.model.Category;
import com.wangzhixuan.model.Describe;
import com.wangzhixuan.model.Image;
import com.wangzhixuan.model.Meeting;
import com.wangzhixuan.model.PeopleWork;
import com.wangzhixuan.model.User;
import com.wangzhixuan.model.vo.AchievementsVo;
import com.wangzhixuan.model.vo.BaseInfoVo;
import com.wangzhixuan.model.vo.DescribeVo;
import com.wangzhixuan.model.vo.ExcelJobInfomationVo;
import com.wangzhixuan.model.wordVo.WordAnalysisVo;
import com.wangzhixuan.model.wordVo.WordMeetingVo;
import com.wangzhixuan.model.wordVo.WordPeopleVo;
import com.wangzhixuan.model.wordVo.WordSurveyVo;
import com.wangzhixuan.service.IBaseInfoService;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhixuan.wang
 * @since 2017-07-19
 */
@Service
public class BaseInfoServiceImpl extends ServiceImpl<BaseInfoMapper, BaseInfo> implements IBaseInfoService {
	
	private final static Logger log= Logger.getLogger(BaseInfoApiController.class);
	
	@Autowired
    private BaseInfoMapper baseInfoMapper;
	
	@Autowired
    private CategoryMapper categoryMapper;
	
	@Autowired
    private PeopleSignMapper peopleSignMapper;
	
	@Autowired
    private AnalysisMapper analysisMapper;
	
	@Autowired
    private ImageMapper imageMapper;
	
	@Autowired
    private UserMapper userMapper;
	
	@Autowired
    private DescribeMapper describeMapper;
    
	@Autowired
    private MeetingMapper meetingMapper;
	
	@Autowired
    private RankMapper rankMapper;
	
	@Autowired
    private PeopleWorkMapper peopleWorkMapper;
	
	@Override
    public void selectDataGrid(PageInfo pageInfo) {
    	Page<Map<String, Object>> page = new Page<Map<String, Object>>(pageInfo.getNowpage(), pageInfo.getSize());
        page.setOrderByField(pageInfo.getSort());
        page.setAsc(pageInfo.getOrder().equalsIgnoreCase("asc"));
        List<BaseInfo> list = baseInfoMapper.selectBaseInfoPage(page, pageInfo.getCondition());
        pageInfo.setRows(list);
        pageInfo.setTotal(page.getTotal());
    }

	@Override
	public boolean insertBaseInfo(BaseInfoVo baseInfoVo) throws MyException {
		
		String[] users = baseInfoVo.getResponsibleArr().split(",");
		int j=0;
		while(j<=users.length){
			if(Integer.valueOf(users[j])==baseInfoVo.getUserId()){
				break;
			}
			j++;
			if(j==4){
				throw new MyException(ApiCode.CODE_500, "负责人必需包含自己！");
			}
		}
		BaseInfo baseInfo = new BaseInfo();
		baseInfo.setCreateId(baseInfoVo.getUserId());
		Category category = categoryMapper.selectById(baseInfoVo.getJobId());
		if(category==null){
			return false;
		}
		TalkDataService service = Entry.getInstance().getTalkApi();
		TalkNode node = null;
		try {
			User user = userMapper.selectById(baseInfoVo.getUserId());
			String[] Ids = baseInfoVo.getResponsibleArr().split(",");
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("list", Ids);
			List<String> listPhone = userMapper.selectPhoneByUserIdArr(paramMap);
			String[] phoneArr = new String[listPhone.size()];
			for(int i =0;i< listPhone.size() ;i++ ){
				phoneArr[i] = listPhone.get(i).toString();
			}
			node = service.groupSave(user.getPhone(), category.getJobName(), category.getJobName(), 300, phoneArr,true,true);
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new MyException(ApiCode.CODE_500, "新建群组信息失败,程序异常");
		}
		if (node.getStatusCode() != 200) {
			throw new MyException(ApiCode.CODE_500, "新建群组信息失败");
		}
    	Map<String,String> params = new HashMap<>();
    	params.put("location", NumberUtils.keepPrecision(baseInfoVo.getPlaceLongitude(), 6)+","+NumberUtils.keepPrecision(baseInfoVo.getPlaceLatitude(), 6));
    	params.put("key", Constants.GAODE_KEY);
		String gaodeAddrStr = HttpClientUtil.sendPostRequest(Constants.GAODE_REQURL, params, "UTF-8", "UTF-8");
		JSONObject jsStr = JSONObject.parseObject(gaodeAddrStr);
		if(!"1".equals(jsStr.get("status").toString())){
			throw new MyException(ApiCode.CODE_500, "高德地图定位失败");
		}
		String mapAddress = ((Map)jsStr.get("regeocode")).get("formatted_address").toString();
		baseInfo.setMapAddress(mapAddress);
		baseInfo.setGroupId(node.getData_group().getGroupid());
		baseInfo.setJobName(category.getJobName());
		baseInfo.setJobCategory(category.getJobCategory());
		baseInfo.setJobDescribe(category.getJobDescribe());
		baseInfo.setStartTime(baseInfoVo.getStartTime());
		baseInfo.setEndTime(baseInfoVo.getEndTime());
		baseInfo.setLineX(baseInfoVo.getPlaceLongitude());
		baseInfo.setLineY(baseInfoVo.getPlaceLatitude());
		baseInfo.setAddress(baseInfoVo.getPlaceName());
		baseInfo.setCreateTime(new Date());
		baseInfo.setResponsibleArr(baseInfoVo.getResponsibleArr());
		//workStatus	工作状态（1.处理中，2.成功，3.失败）
		baseInfo.setStatus("1");
		baseInfo.setSurveyStatus(301); //现场勘察还未开始
		baseInfoMapper.insert(baseInfo);
		

//		PeopleSign peopleSign = null;
//		for(Integer userId : baseInfoVo.getResponsibleArr()){
//			peopleSign = new PeopleSign();
//			peopleSign.setWorkId(baseInfo.getId());
//			peopleSign.setUserId(userId);
//			peopleSign.setStatus("0");
//			peopleSignMapper.insert(peopleSign);
//		}
		return true;
	}
	
	

	@Override
	public List<Map<String, Object>> selectList(Integer userId,
			String statusQuery, String personnelQuery,String today) throws ParseException {
		Map<String,Object> paramMap = new HashMap<>();
		//personnelQuery	string	是	人员查询（1.自己，2.所有人）
		paramMap.put("userId", userId);
		paramMap.put("statusQuery", statusQuery);
		paramMap.put("date", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
		System.out.println(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM));
		if(today==null){
			if("1".equals(personnelQuery)){
				return baseInfoMapper.selectList(paramMap);
			}
			return baseInfoMapper.selectAllList(paramMap);
		}
		else{
		    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年-MM月-dd日 HH:mm:ss");  
		    Date date = sdf.parse(today);
		    paramMap.put("today", DateUtil.DateToString(date, DateStyle.YYYY_MM_DD));
			if("1".equals(personnelQuery)){
				return baseInfoMapper.selectTodayList(paramMap);
			}
			return baseInfoMapper.selectTodayAllList(paramMap);
		}

	}

	@Override
	public Map<String, Object> selectWorkDetail(Integer workId,Integer userId) throws Exception {
		Map<String,Object> map = new HashMap<String,Object>();
		BaseInfo baseInfo = baseInfoMapper.selectById(workId);
		if(baseInfo==null){
			throw new MyException(ApiCode.CODE_500, "网络异常，请重新开始任务");
		}
		User selectById = userMapper.selectById(userId);
		map.put("releaseMan", selectById.getName());
		map.put("releaseManID", baseInfo.getCreateId());
		System.out.println(baseInfo.getCreateId());
		map.put("surveyStatus", baseInfo.getSurveyStatus());
		map.put("jobName", baseInfo.getJobName());
		map.put("jobCategory", baseInfo.getJobCategory());
		map.put("jobDescrib", baseInfo.getJobDescribe());
		map.put("startTime", baseInfo.getStartTime());
		map.put("endTime", baseInfo.getEndTime());
		map.put("placeName", baseInfo.getAddress());
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("workId", workId);
		paramMap.put("userId", userId);
		paramMap.put("curDate", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
		String signName = peopleSignMapper.selectCurDateSign(paramMap);
		map.put("signName", signName==null?"":signName);
		Meeting meeting = meetingMapper.selectMeetForBase(userId, workId);   //在后来的版本中去掉了userId,实际只用了workId查询
		if(meeting!=null)
		{
			if("11".equals(meeting.getType())){
				map.put("afterMeeting","301"); //301未开始302进行中303结束
				if("21".equals(meeting.getStatus())){
					map.put("frontMeeting", "301");
				}
				if("22".equals(meeting.getStatus())){
					map.put("frontMeeting", "302");
				}
				if("23".equals(meeting.getStatus())){
					map.put("frontMeeting", "303");
				}
			}
			if("12".equals(meeting.getType())){
				map.put("frontMeeting", "303");
				if("21".equals(meeting.getType())){
					map.put("afterMeeting", "301");
				}
				if("22".equals(meeting.getType())){
					map.put("afterMeeting", "302");
				}
				if("23".equals(meeting.getType())){
					map.put("afterMeeting", "303");
				}
			}
		}
		else{
			map.put("afterMeeting","301");
			map.put("frontMeeting","301");
		}
		Map<String,Object> ponDetailsMap = analysisMapper.selectPhenomenonByWorkId(workId);
		if(ponDetailsMap==null){
			map.put("ponDetails", "");
			map.put("ponId", "");
		}else{
			map.put("ponDetails", ponDetailsMap.get("name")==null?"":ponDetailsMap.get("name").toString());
			map.put("ponId", ponDetailsMap.get("id").toString());
		}
		String responsibleArrStr = baseInfo.getResponsibleArr();
		if(responsibleArrStr!=null){
			String[] userArr = responsibleArrStr.split(",");
			Map<String,Object> userMap = new HashMap<String,Object>();
			userMap.put("list", userArr);
			List<Map<String,Object>> resList = userMapper.selectByUserIdArr(userMap);
			map.put("responsibleArr", resList);
		}else{
			map.put("responsibleArr", new ArrayList());
		}
		List<Map<String,Object>> listMethods = analysisMapper.selectReasonByWorkId(workId);
		List<Map<String, Object>> selectPonByWorkId = analysisMapper.selectPonByWorkId(workId);
//		if(listMethods!=null & listMethods.size()>0){
			map.put("methodArr", listMethods);
			map.put("ponName", selectPonByWorkId);
//		}
		if(Constants.WORK_STATUS.STATUS6.equals(baseInfo.getStatus())){
			map.put("finStatus", "2");
		}else if(Constants.WORK_STATUS.STATUS7.equals(baseInfo.getStatus())){
			map.put("finStatus", "3");
		}else if(Constants.WORK_STATUS.STATUS5.equals(baseInfo.getStatus())){
			map.put("finStatus", "1");
		}else{
			map.put("finStatus", "0");     //0未开始1工作中
		}
		Describe desDescrib = describeMapper.selectLastOnebyWorkId(workId);
		if(desDescrib!=null){
			map.put("desDescrib", desDescrib.getNotes()==null?"":desDescrib.getNotes());
			Map<String,Object> imgParam = new HashMap<String,Object>();
			imgParam.put("workId", workId);
			imgParam.put("descId", desDescrib.getId());
			List<String> listImg = imageMapper.selectByDesIdAndWorkId(imgParam);
//		if(listImg!=null && listImg.size()>0){
			map.put("desPictureArr", listImg);
//		}
		}else{
			map.put("desDescrib", "");
			map.put("desPictureArr", new ArrayList<>());
		}
		return map;
	}

	@Override
	public void insertDescribe(BaseInfo baseInfo, DescribeVo describeVo) {
    	baseInfo.setWorkNotes(describeVo.getDesDescrib());
    	baseInfo.setWorkCreateId(describeVo.getUserId());
    	baseInfoMapper.updateById(baseInfo);
    	Image image = null;
    	for(String str : describeVo.getDesPictureArrList()){
    		image = new Image();
    		image.setCreateId(describeVo.getUserId());
    		image.setWorkId(describeVo.getWorkId());
    		image.setImgPath(str);
    		image.setType("3");
    		image.setCreateTime(new Date());
    		imageMapper.insert(image);
    	}
	}

	@Override
	public List<Map<String, Object>> selectAddressList() {
		return baseInfoMapper.selectAddressList();
	}

	@Override
	public Map<String, Object> selectAchievementsDetail(
			AchievementsVo achievementsVo) {
		Date beginTime = achievementsVo.getBeginTime();
		Date endingTime = achievementsVo.getEndingTime();
		Integer userId = achievementsVo.getUserId();
		HashMap<String, Object> paramMap = new HashMap<String,Object>();
		paramMap.put("beginTime", beginTime);
		paramMap.put("endingTime", endingTime);
		paramMap.put("userId", userId);
		float onTimeNum = baseInfoMapper.selectOnTimeNum(paramMap);
		float notNum = baseInfoMapper.selectNotNum(paramMap);
		float delayTimeNum = baseInfoMapper.selectDelayTimeNum(paramMap);
		float add = onTimeNum+delayTimeNum;
		float onTimeRate = (float) (onTimeNum/add);
		if(onTimeNum==0||add==0){
			onTimeRate = 0;
		}
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		Integer ranking = rankMapper.selectUserRank(userId);
		if(ranking==null){
			resultMap.put("ranking", 0);
			resultMap.put("totalOnTimeNum", 0);
			resultMap.put("onTimeNum", 0);
			resultMap.put("notNum", 0);
			resultMap.put("delayTimeNum", 0);
			resultMap.put("onTimeRate", 0);
			resultMap.put("workNumber",0);
			return resultMap;
		}
		//int totalOnTimeNum = rankMapper.selectUserTotalOnTimeNum(userId);
		float totalOnTimeNum = baseInfoMapper.selectUserTotalOnTimeNum(paramMap);
		resultMap.put("ranking", ranking);
		resultMap.put("totalOnTimeNum", (int)totalOnTimeNum);
		resultMap.put("onTimeNum", onTimeNum);
		resultMap.put("notNum", notNum);
		resultMap.put("delayTimeNum", delayTimeNum);
		resultMap.put("onTimeRate", onTimeRate*100);
		resultMap.put("workNumber",(int)(onTimeNum+notNum+delayTimeNum));
		return resultMap;
	}

	/**
	 * 消息推送
	 */
	@Override
	public void sendPush(Integer userId, Integer workId) {
		User selectUserById = userMapper.selectById(userId);//消息推送	
		String phone = selectUserById.getPhone();
		BaseInfo baseInfo = baseInfoMapper.selectById(workId);
		
		PushUtils.sendPush(phone,"与您相关的"+baseInfo.getJobCategory()+"的"
		+baseInfo.getJobName()+"已开始工作", workId.toString());						//推送结束
	}
	
	/**
	 * 生成WORD
	 * @throws Exception 
	 */
	@Override
	public String selectWord(Integer workId,String getRootPath,String getbaseUrl) throws Exception {
		ExcelJobInfomationVo excelJobInfo = baseInfoMapper.selectExJobInfo(workId);
		WordSurveyVo wdSurvey = baseInfoMapper.selectWdSurvey(workId);
		WordMeetingVo wdMeeting = baseInfoMapper.selectWdMeeting(workId);
		List<WordAnalysisVo> wdAnalysis = baseInfoMapper.selectWdAnalysis(workId);
		List<String> wdPhenom = baseInfoMapper.selectWdPhenom(workId);
		List<WordPeopleVo> wdPeople = baseInfoMapper.selectWdPeople(workId);
		List<String> imgPath = baseInfoMapper.selectImgPath(workId);
		CreatWordFtl creatWordFtl = new CreatWordFtl();
		String wordUrl = creatWordFtl.exportListWord(excelJobInfo,wdSurvey,wdMeeting,wdAnalysis,wdPhenom,wdPeople,imgPath,getRootPath,getbaseUrl);
		//CreatDoc.CreatWord(excelJobInfo,wdSurvey,wdMeeting,wdAnalysis,wdPhenom,wdPeople,imgPath,getRootPath,getbaseUrl); 
		return wordUrl;
	}

	@Override
	public Integer selectAllBaseInfo(BaseInfoVo baseInfoVo) {
		HashMap<String, Object> paramMap = new HashMap<String,Object>();
		Date endTime = baseInfoVo.getEndTime();
		String placeLatitude = baseInfoVo.getPlaceLatitude();
		String placeLongitude = baseInfoVo.getPlaceLongitude();
		String placeName = baseInfoVo.getPlaceName();
		Date startTime = baseInfoVo.getStartTime();
		paramMap.put("endTime", endTime);
		paramMap.put("startTime", startTime);
		paramMap.put("placeLatitude", placeLatitude);
		paramMap.put("placeLongitude", placeLongitude);
		paramMap.put("placeName", placeName);
		Integer integer = baseInfoMapper.selectAllBaseInfo(paramMap);
		return integer;
	}

	@Override
	public BaseInfo selectGroup(String groupId) {
		BaseInfo group = baseInfoMapper.selectGroup(groupId);
		return group;
	}

	@Override
	public List<Map<String, Object>> selectUserGroup(Integer userId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Map<String, Object>> selecListtByJobCategory(String jobCategory) {
		List<Map<String, Object>> list = baseInfoMapper.selecListtByJobCategory(jobCategory);
		return list;
	}

}
